package com.demo.netty.protobuf;

import com.demo.netty.model.RichManProto;
import com.demo.netty.tcp.TcpHandler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import org.apache.log4j.Logger;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.List;

/**
 * Created by carlkong on 2016/7/21.
 */
public class ProtoBufServerHandler extends ChannelHandlerAdapter {
    private static final Logger logger = Logger.getLogger(TcpHandler.class);
    //获取收到的信息
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        InetAddress remoteAddr = ((InetSocketAddress)ctx.channel().remoteAddress()).getAddress();
        int remotePort = ((InetSocketAddress)ctx.channel().remoteAddress()).getPort();
        String remoteIp=remoteAddr.getHostAddress();
        RichManProto.RichMan req = (RichManProto.RichMan) msg;

        System.out.println(req.getName()+"他有"+req.getCarsCount()+"量车");

        List<RichManProto.RichMan.Car> lists = req.getCarsList();
        if(null != lists) {

            for(RichManProto.RichMan.Car car : lists){
                System.out.println(car.getName());
            }
        }

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }
    //异常处理
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        ByteBuf response=null;

        ctx.write(response);
        logger.error( "Unexpected exception from tcp request"+cause.getMessage());
        ctx.close();
    }
}
